package com.fish.web.controller;

import com.fish.common.result.PageResult;
import com.fish.common.result.Result;
import com.fish.model.dto.ChatMessageDTO;
import com.fish.model.dto.ChatMessageQueryDTO;
import com.fish.model.vo.ChatMessageVO;
import com.fish.model.vo.ChatSessionVO;
import com.fish.service.ChatService;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 聊天控制器
 *
 * @author fish
 */
@Tag(name = "聊天管理", description = "聊天消息和会话管理相关接口")
@Slf4j
@RestController
@RequestMapping("/api/chat")
@RequiredArgsConstructor
public class ChatController {

    private final ChatService chatService;

    /**
     * 发送消息
     */
    @PostMapping("/send")
    public Result<ChatMessageVO> sendMessage(@RequestBody ChatMessageDTO chatMessageDTO) {
        ChatMessageVO messageVO = chatService.sendMessage(chatMessageDTO);
        return Result.success(messageVO);
    }

    /**
     * 获取会话列表
     */
    @GetMapping("/sessions")
    public Result<List<ChatSessionVO>> getSessionList() {
        List<ChatSessionVO> sessionList = chatService.getSessionList();
        return Result.success(sessionList);
    }

    /**
     * 获取历史消息
     */
    @GetMapping("/messages")
    public Result<PageResult<ChatMessageVO>> getMessageList(ChatMessageQueryDTO queryDTO) {
        PageResult<ChatMessageVO> messageList = chatService.getMessageList(queryDTO);
        return Result.success(messageList);
    }

    /**
     * 标记消息为已读
     */
    @PutMapping("/read/{sessionId}")
    public Result<Void> markMessagesAsRead(@PathVariable Long sessionId) {
        chatService.markMessagesAsRead(sessionId);
        return Result.success();
    }

    /**
     * 获取或创建会话
     */
    @PostMapping("/session/{otherUserId}")
    public Result<Long> getOrCreateSession(@PathVariable Long otherUserId) {
        Long sessionId = chatService.getOrCreateSession(
                com.fish.common.util.UserContext.getUserId(),
                otherUserId
        );
        return Result.success(sessionId);
    }
}

